package com.example.demo.controller;

import com.example.demo.common.HTTPResult;
import com.example.demo.common.ArtTimeUtil;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.component.ArtThreadPoolExecutor;
import com.example.demo.entity.Articleinfo;
import com.example.demo.entity.Time;
import com.example.demo.entity.Userinfo;
import com.example.demo.entity.vo.TimeVO;
import com.example.demo.service.ArticleService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 */
@RestController
@RequestMapping("/art")
public class ArtController {
    @Autowired
    private ArticleService articleService;

    // 将线程池注入
    @Autowired
    private ArtThreadPoolExecutor executors;

    // 根据用户 id、page、size 获取他的博客信息
    @RequestMapping("/mylist")
    public HTTPResult getMyList(HttpServletRequest request, Integer page, Integer size) {
        Userinfo userinfo = UserSessionUtils.getUserBySession(request);
        if(userinfo == null) {
            return HTTPResult.fail(-1, "非法请求");
        }
        // 判断页码是否存在，如果不存在将其校正为首页
        if(page == null || page <= 1) {
            page = 1;
        }
        // 判断用户是否传递了需要展示的一页的博客数量
        if(size == null || size <= 1) {
            size = 3;
        }
        List<Articleinfo> list = articleService.getMyList(userinfo.getId(), (page - 1) * size, size);
        for (Articleinfo articleinfo : list) {
            if(articleinfo.getContent().length() > 200) {
                articleinfo.setContent(articleinfo.getContent().substring(0, 100) + "...");
            }
        }
        // 获取所有博客数量
        Integer count = articleService.getArtCountByUid(userinfo.getId());
        // 根据博客数量和每页的条数计算总共的页数，Math.ceil保证只要小数位有数，都进1
        Integer pageCount = (int)Math.ceil(count / (size * 1.0));
        // 把一页的博客和博客页数都放到 HashMap 中进行返回
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("pageCount", pageCount);
        return HTTPResult.success(map);
    }

    // 根据用户 id、state、start、size查询用户草稿，按照修改时间降序获得
    @RequestMapping("/mydraftlist")
    public HTTPResult getDraftList(Integer page, Integer size, HttpServletRequest request) {
        // 身份校验
        Userinfo userinfo = UserSessionUtils.getUserBySession(request);
        if(userinfo == null) {
            return HTTPResult.fail(-1, "非法请求");
        }
        // 参数校正
        if(page == null || page < 1) {
            page = 1;
        }
        if(size == null || size <= 1) {
            size = 3;
        }
        // 获取草稿信息并截取正文
        List<Articleinfo> list =
                articleService.getMyDraftList(userinfo.getId(), (page - 1) * size, size);
        for (Articleinfo articleinfo : list) {
            if(articleinfo.getContent().length() > 200) {
                articleinfo.setContent(articleinfo.getContent().substring(0, 100) + "...");
            }
        }
        // 获取草稿数量
        Integer count = articleService.getDraftCountByUid(userinfo.getId());
        // 根据草稿数量计算草稿页数
        Integer pageCount = (int) Math.ceil((count * 1.0) / size);
        // 创建 HashMap 保存并返回结果
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("pageCount", pageCount);
        return HTTPResult.success(map);
    }

    // 根据博客 id 逻辑删除博客信息
    @RequestMapping("/del")
    public HTTPResult del(Integer id, HttpServletRequest request) {
        if(id == null || id <= 0) {
            // 参数有误
            return HTTPResult.fail(-1, "参数异常");
        }
        Userinfo userinfo = UserSessionUtils.getUserBySession(request);
        if(userinfo == null) {
            return HTTPResult.fail(-2, "用户未登录");
        }
        Integer uid = userinfo.getId();
        Integer result = articleService.del(id, uid);
        return HTTPResult.success(result);
    }

    // 根据文章 id 获取文章详情信息
    @RequestMapping("/detail")
    public HTTPResult getDetail(Integer id) {
        if(id == null || id <= 0) {
            return HTTPResult.fail(-1, "参数异常");
        }
        return HTTPResult.success(articleService.getDetail(id));
    }

    // 根据文章 id 获取文章详情信息
    // 该接口获取文章信息前必须经过身份校验，并且判断该 id 对应的文章中的 uid 是否和 Session 中的 Uid 相同
    @RequestMapping("/mydetail")
    public HTTPResult getMyDetail(Integer id, HttpServletRequest request) {
        if(id == null || id <= 0) {
            return HTTPResult.fail(-1, "参数异常");
        }
        Userinfo userinfo = UserSessionUtils.getUserBySession(request);
        if(userinfo == null) {
            return HTTPResult.fail(-1, "非法请求");
        }
        return HTTPResult.success(articleService.getMyDetail(id, userinfo.getId()));
    }

    // 根据文章 id 将文章阅读量自增
    @RequestMapping("/incr-rcount")
    public HTTPResult addRcountById(@Param("id") Integer id) {
        if(id == null || id <= 0) {
            return HTTPResult.fail(-1, "参数异常");
        }
        return HTTPResult.success(articleService.addRcountById(id));
    }

    // 新增文章操作
    @RequestMapping("/addart")
    public HTTPResult addArticle(Articleinfo articleinfo, HttpServletRequest request) {
        // 非空校验
        if(articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle()) ||
                !StringUtils.hasLength(articleinfo.getContent())) {
            return HTTPResult.fail(-1, "参数异常");
        }
        // 获取 uid
        Userinfo userinfo = UserSessionUtils.getUserBySession(request);
        if(userinfo == null || userinfo.getId() <= 0) {
            return HTTPResult.fail(-2, "非法请求");
        }
        articleinfo.setUid(userinfo.getId());
        // 添加文章数据
        return HTTPResult.success(articleService.addArticle(articleinfo));
    }

    // 新增定时发布文章操作
    @RequestMapping("/add_time_art")
    public HTTPResult addTimeArticle(Articleinfo articleinfo, Time time, HttpServletRequest request) {
        // 身份校验
        Userinfo userinfo = UserSessionUtils.getUserBySession(request);
        if(userinfo == null) {
            return HTTPResult.fail(-2, "非法请求");
        }
        // 非空校验
        if(articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle()) ||
                !StringUtils.hasLength(articleinfo.getContent())) {
            return HTTPResult.fail(-1, "参数异常");
        }
        // 校正时间
        ArtTimeUtil.timeCheck(time);
        // 设置博客 uid
        articleinfo.setUid(userinfo.getId());
        // 设置博客创建时间和修改时间
        articleinfo.setCreatetime(ArtTimeUtil.getTimeToLocalDateTime(time));
        articleinfo.setUpdatetime(ArtTimeUtil.getTimeToLocalDateTime(time));
        // 添加文章数据
        Integer result = articleService.addTimeArticle(articleinfo);
        // 将修改状态操作加入线程池
        executors.put(new Runnable() {
            @Override
            public void run() {
                articleinfo.setState(1);
                articleService.updateArticleState(articleinfo);
            }
        }, time);
        return HTTPResult.success(result);
    }

    // 修改文章内容
    @RequestMapping("/update")
    public HTTPResult updateArticle(HttpServletRequest request, Articleinfo articleinfo) {
        if(articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle()) ||
                !StringUtils.hasLength(articleinfo.getContent())) {
            return HTTPResult.fail(-1, "参数异常");
        }
        Userinfo userinfo = UserSessionUtils.getUserBySession(request);
        if(userinfo == null || !userinfo.getId().equals(articleinfo.getUid())) {
            return HTTPResult.fail(-2, "非法请求");
        }
        return HTTPResult.success(articleService.updateArticle(articleinfo));
    }

    /**
     * 根据页码和一页的最大博客数量来获取之后的博客内容，按照时间降序获取
     * @param page 当前页码（从 1 开始）
     * @param size 每一页的条数
     * @return
     */
    @RequestMapping("/getlist")
    public HTTPResult getList(Integer page, Integer size) {
        // 判断页码是否存在，如果不存在将其校正为首页
        if(page == null || page <= 1) {
            page = 1;
        }
        // 判断用户是否传递了需要展示的一页的博客数量
        if(size == null || size <= 1) {
            size = 5;
        }
        // 获取到对应页的博客列表
        List<Articleinfo> list = articleService.getList((page - 1) * size, size);
        for (Articleinfo articleinfo : list) {
            if(articleinfo.getContent().length() > 200) {
                articleinfo.setContent(articleinfo.getContent().substring(0, 100) + "...");
            }
        }
        // 获取所有博客数量
        Integer count = articleService.getArtCountByUid(null);
        // 根据博客数量和每页的条数计算总共的页数，Math.ceil保证只要小数位有数，都进1
        Integer pageCount = (int)Math.ceil(count / (size * 1.0));
        // 把一页的博客和博客页数都放到 HashMap 中进行返回
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("pageCount", pageCount);
        return HTTPResult.success(map);
    }

    // 保存草稿
    @RequestMapping("insertdraft")
    public HTTPResult insertDraft(Articleinfo articleinfo, HttpServletRequest request) {
        // 用户信息校验
        Userinfo userinfo = UserSessionUtils.getUserBySession(request);
        if (userinfo == null) {
            return HTTPResult.fail(-1, "非法请求");
        }
        // 文章参数校验
        if(!StringUtils.hasLength(articleinfo.getTitle()) ||
                !StringUtils.hasLength(articleinfo.getContent())) {
            return HTTPResult.fail(-1, "参数异常");
        }
        // 为了安全与适应从新增博客页面发过来的没有 uid 的请求，将 session 中的 id 设置成文章的 uid
        articleinfo.setUid(userinfo.getId());
        // 判断文章 id 是否存在，为了安全，如果文章 id 存在，判断 uid 是否相同
        if(articleinfo.getId() == null) {
            // 第一次保存草稿
            Integer result = articleService.addDraft(articleinfo);
            return HTTPResult.success(result);
        }else {
            // 修改时对 uid 进行判断比较
            Integer result = articleService.updateArticle(articleinfo);
            return HTTPResult.success(result);
        }


    }
}
